package cn.xiaopengstack.infrastructure.persistent.repository;

import cn.xiaopengstack.domain.activity.model.valobj.UserGroupBuyOrderVO;
import cn.xiaopengstack.domain.activity.repository.IGroupBuyOrderRepository;
import cn.xiaopengstack.infrastructure.persistent.dao.IGroupBuyOrderDao;
import cn.xiaopengstack.infrastructure.persistent.dao.IGroupBuyOrderListDao;
import cn.xiaopengstack.infrastructure.persistent.po.GroupBuyOrder;
import cn.xiaopengstack.infrastructure.persistent.po.GroupBuyOrderList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author jiangyangang
 */
@Repository
@Slf4j
public class GroupBuyOrderRepository implements IGroupBuyOrderRepository {

    @Resource
    private IGroupBuyOrderListDao groupBuyOrderListDao;

    @Resource
    private IGroupBuyOrderDao groupBuyOrderDao;

    @Override
    public List<UserGroupBuyOrderVO> queryUserGroupOrderList(String userId) {

        List<GroupBuyOrderList> groupBuyOrderList = groupBuyOrderListDao.queryListByUserId(userId);

        if (CollectionUtils.isEmpty(groupBuyOrderList)) {
            return Collections.emptyList();
        }
        List<UserGroupBuyOrderVO> groupBuyOrderVOList = new ArrayList<>();
        groupBuyOrderList.forEach((orderList) -> {

            GroupBuyOrder groupBuyOrder = groupBuyOrderDao.queryRemainNumberByTeamId(orderList.getTeamId());
            if (Objects.isNull(groupBuyOrder)) {
                return ;
            }

            UserGroupBuyOrderVO userGroupBuyOrderVO = UserGroupBuyOrderVO
                    .builder()
                    .teamId(orderList.getTeamId())
                    .orderId(orderList.getOrderId())
                    .orderStatus(orderList.getStatus())
                    .currentTeamNumber(groupBuyOrder.getCompleteCount())
                    .remainingTeamNumber(groupBuyOrder.getTargetCount() - groupBuyOrder.getCompleteCount())
                    .teamStatus(groupBuyOrder.getStatus())
                    .activityId(groupBuyOrder.getActivityId())
                    .build();

            groupBuyOrderVOList.add(userGroupBuyOrderVO);
        });



        return groupBuyOrderVOList;
    }
}
